from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# from .models import Booktitle, Userinfo
from .models import Booktitle, BookSection
from userbook.models import Userinfo, Userintroduce
from django.views.decorators.http import require_POST
import json

@csrf_exempt
def add_book(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        try:
            user_uuid = data.get('author_uuid')
            # 看看是不是有这个人
            author = Userinfo.objects.get(uuid=user_uuid)
            print(author)

            book = Booktitle.objects.create(
                name=data.get('name'),
                portrait=data.get('portrait', None),
                # publish_time=data.get('publish_time', None),
                # frequency=data.get('frequency', 0),
                author=author,
            )
            return JsonResponse({'status': 'success', 'book_uuid': book.bookUuid})
        except Userinfo.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': 'Author not found'}, status=400)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)



@csrf_exempt
def add_book_chapter(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        try:
            book_uuid = data.get('book_uuid')
            book = Booktitle.objects.get(bookUuid=book_uuid)
            print(book)

            chapter = BookSection.objects.create(
                nametitle=data.get('nametitle'),
                content=data.get('content'),
                book=book
            )
            return JsonResponse({'status': 'success', 'chapter_uuid': chapter.titleUuid})
        except Booktitle.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': 'Book not found'}, status=400)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)


@csrf_exempt
@require_POST
def get_book_by_uuid(request):
    # 解析请求数据
    try:
        data = json.loads(request.body.decode('utf-8'))
    except json.JSONDecodeError:
        return JsonResponse({'error': '无效的请求数据'}, status=400)

    # 从请求数据中获取图书UUID
    book_uuid = data.get('uuid')

    if not book_uuid:
        return JsonResponse({'error': 'uuid无效'}, status=400)

    try:
        # 查找图书信息
        book = Booktitle.objects.get(bookUuid=book_uuid)
    except Booktitle.DoesNotExist:
        return JsonResponse({'error': '图书不存在'}, status=404)

    # 查找图书章节信息
    chapters = BookSection.objects.filter(book=book).values('titleUuid', 'nametitle')

    # 组装图书数据
    book_info = {
        'name': book.name,
        'portrait': book.portrait.url if book.portrait else None,
        'book_time': book.book_time.isoformat(),
        'publish_time': book.publish_time.isoformat() if book.publish_time else None,
        'frequency': book.frequency,
        'bookUuid': book.bookUuid,
        'author': book.author.uuid,  # Assuming Userinfo has a 'uuid' field
        'chapters': list(chapters),
    }

    # 返回 JSON 响应
    return JsonResponse({'book': book_info}, safe=False)

@csrf_exempt
@require_POST
def get_book_chapter(request):
    try:
        # 解析请求数据
        data = json.loads(request.body.decode('utf-8'))
    except json.JSONDecodeError:
        return JsonResponse({'error': '无效的JSON数据'}, status=400)

    # 获取传递的UUID
    chapter_uuid = data.get('uuid')
    if not chapter_uuid:
        return JsonResponse({'error': 'UUID无效'}, status=400)

    try:
        # 查找章节信息
        chapter = BookSection.objects.get(titleUuid=chapter_uuid)
    except BookSection.DoesNotExist:
        return JsonResponse({'error': '章节不存在'}, status=404)
    # 获取图书信息,chapter.book这是一个实例就是已经对应了直接访问bookUuid就行
    book = Booktitle.objects.get(bookUuid=chapter.book.bookUuid)

    # 获取作者信息
    author = Userinfo.objects.get(uuid=book.author.uuid)

    # 组装返回的数据
    book_info = {
        'title': chapter.nametitle,
        'content': chapter.content,
        'titleUuid': chapter.titleUuid,
        'bookName': book.name,
        'bookUuid': book.bookUuid,
        'authorName': author.name
    }

    return JsonResponse({'book': book_info}, safe=False)

